﻿﻿@model verk2013_project_group12.Models.GameInstance
@{
    ViewBag.Title = "Yahtzee";
}

@section JavaScript
{
    <script src="@Url.Content("~/Scripts/jquery.signalR-1.0.1.min.js")" type="text/javascript"></script>
     <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
}

@{Html.RenderPartial("_Chat");}

<h2>Yahtzee!</h2>




<div id="yahtzeeGame">

    <input type="checkbox" name="dice" value="dice1" id="box1" class="yahtzeeCheckbox" /><span id="dice1Img"> </span><span id="dice1">Press Roll button</span>
    <input type="checkbox" name="dice" value="dice2" id="box2" class="yahtzeeCheckbox" /><span id="dice2Img"> </span><span id="dice2">Press Roll button</span>
    <input type="checkbox" name="dice" value="dice3" id="box3" class="yahtzeeCheckbox" /><span id="dice3Img"> </span><span id="dice3">Press Roll button</span>
    <input type="checkbox" name="dice" value="dice4" id="box4" class="yahtzeeCheckbox" /><span id="dice4Img"> </span><span id="dice4">Press Roll button</span>
    <input type="checkbox" name="dice" value="dice5" id="box5" class="yahtzeeCheckbox" /><span id="dice5Img"> </span><span id="dice5">Press Roll button</span>

    <div>
        <span><input type="button" value="Roll" name="roll" id="roll" class="buttonBox buttonShadowBox"/></span><span id="turnInfo"><strong>Please wait for your turn</strong></span>
    </div>
    <p>Roll number <span id="numberOfRolls">1</span></p>

    <h3>Upper section</h3>
    <div class="upperPos">
        <input type="button" value="1" name="upperSection" id="ones" class="buttonBox buttonShadowBox"/>
        <input type="button" value="2" name="upperSection" id="twos" class="buttonBox buttonShadowBox" />
        <input type="button" value="3" name="upperSection" id="threes" class="buttonBox buttonShadowBox" />
        <input type="button" value="4" name="upperSection" id="fours" class="buttonBox buttonShadowBox" />
        <input type="button" value="5" name="upperSection" id="fives" class="buttonBox buttonShadowBox" />
        <input type="button" value="6" name="upperSection" id="sixes" class="buttonBox buttonShadowBox" />
    </div>

    <h3>Lower section</h3>
    <div>
        <input type="button" value="3 of a kind" name="lowerSection" id="trips" class="buttonBox buttonShadowBox"/>
        <input type="button" value="4 of a kind" name="lowerSection" id="quads" class="buttonBox buttonShadowBox"/>
        <input type="button" value="Full house" name="lowerSection" id="boat" class="buttonBox buttonShadowBox"/>
        <input type="button" value="Small straight" name="lowerSection" id="smallStraight" class="buttonBox buttonShadowBox"/>
        <input type="button" value="Large straight" name="lowerSection" id="largeStraight" class="buttonBox buttonShadowBox"/>
    </div>
    <div class="chanceYahtzeePos">
        <input type="button" value="Chance" name="lowerSection" id="chance" class="buttonBox buttonShadowBox"/>
        <input type="button" value="Yahtzee" name="lowerSection" id="yahtzee" class="buttonBox buttonShadowBox"/>
    </div>

    <div>
        <span><input type="button" value="Submit" name="submit" id="submit" class="buttonBox buttonShadowBox"/></span>
    </div>
    <h3>Roll score</h3>
    <p id="rollScore">0</p>

    <h3>Total score</h3>
    <p id="totalScore">0</p>

</div>
<div class="scorecard">
        <table id="scoreboard">
            <thead>
              <tr>
                  <th>Players</th>
                  <th>1</th>
                  <th>2</th>
                  <th>3</th>
                  <th>4</th>
                  <th>5</th>
                  <th>6</th>
                  <th>Trips</th>
                  <th>Quads</th>
                  <th>F. house</th>
                  <th>S. straight</th>
                  <th>L. straight</th>
                  <th>Chance</th>
                  <th>Yahtzee</th>
                  <th>Bonus</th>
                  <th></th>
                  <th><strong>Total</strong></th>
              </tr>
            </thead>
            <tbody id="players">
           </tbody>   
        </table>
    </div>


<script>
    $(document).ready(function () {
        $(".playerList").hide();
        $(".leaderboard").hide();
        $("#menu").hide();

        function rollDice() {
            // Gives each dice a value between 1-6
            var randomNumber = 0;
            for (var i = 1; i <= 5; i++) {
                if (!($("#box" + i.toString()).is(":checked"))) {
                    randomNumber = Math.floor(Math.random() * 6) + 1;
                    $("#dice" + i.toString()).html(randomNumber);
                    $("#dice" + i + "Img").html('<img src="/Images/dice' + randomNumber + '.png" alt="dice-' + i + '" width="50" height="50" />');
                    $("#dice" + i).hide();
                }
            }
        }

        // Following functions calculate the roll score
        function calcScore(theNumber) {
            // This function covers the upper section
            theScore = 0;
            for (var i = 1; i <= 5; i++) {
                if (theNumber == parseInt($("#dice" + i.toString()).text())) {
                    theScore = theScore + theNumber;
                }
            }
            return theScore;
        }

        function calcTrips() { /* foreloop that checks if three instances of the same dice are present on the board using a counter*/
            var count = 0;
            for (var i = 1; i <= 6; i++) {
                for (var j = 1; j <= 5; j++) {
                    if (parseInt($("#dice" + j.toString()).text()) == i) {
                        count++;
                        if (count == 3) {
                            return calcChance();
                        }
                    }
                }
                count = 0;
            }
            return 0;
        }

        function calcQuads() { /* same as trips but the loop looks for four dice*/
            var count = 0;
            for (var i = 1; i <= 6; i++) {
                for (var j = 1; j <= 5; j++) {
                    if (parseInt($("#dice" + j.toString()).text()) == i) {
                        count++;
                        if (count == 4) {
                            return calcChance();
                        }
                    }
                }
                count = 0;
            }
            return 0;
        }

        function calcBoat() { /* checks if the player has two of the same dive and then three of the of the same dice and vice versa*/
            // Full house
            var theScore = 0;

            var i = [];

            i[0] = parseInt($("#dice1").text());
            i[1] = parseInt($("#dice2").text());
            i[2] = parseInt($("#dice3").text());
            i[3] = parseInt($("#dice4").text());
            i[4] = parseInt($("#dice5").text());

            i.sort();

            if ((((i[0] == i[1]) && (i[1] == i[2])) && // Three of a Kind
                 (i[3] == i[4]) && // Two of a Kind
                 (i[2] != i[3])) ||
                ((i[0] == i[1]) && // Two of a Kind
                 ((i[2] == i[3]) && (i[3] == i[4])) && // Three of a Kind
                 (i[1] != i[2]))) {
                theScore = 25;
            }

            return theScore;
        }

        function calcSmallStraight() {
            var theScore = 0;

            var i = []; // put the dice in an array

            i[0] = parseInt($("#dice1").text());
            i[1] = parseInt($("#dice2").text());
            i[2] = parseInt($("#dice3").text());
            i[3] = parseInt($("#dice4").text());
            i[4] = parseInt($("#dice5").text());

            i.sort();

            // Problem can arise hear, if there is more than one of the same number, so
            // we must move any doubles to the end
            for (var j = 0; j < 4; j++) {
                var temp = 0;
                if (i[j] == i[j + 1]) {
                    temp = i[j];

                    for (var k = j; k < 4; k++) {
                        i[k] = i[k + 1];
                    }

                    i[4] = temp;
                }
            }

            if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4)) || //all the instances that make up a small straight
                ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5)) ||
                ((i[0] == 3) && (i[1] == 4) && (i[2] == 5) && (i[3] == 6)) ||
                ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4)) ||
                ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5)) ||
                ((i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))) {
                theScore = 30;
            }

            return theScore;
        }

        function calcLargeStraight() {
            var theScore = 0;

            var i = []; // same as in small straight.

            i[0] = parseInt($("#dice1").text());
            i[1] = parseInt($("#dice2").text());
            i[2] = parseInt($("#dice3").text());
            i[3] = parseInt($("#dice4").text());
            i[4] = parseInt($("#dice5").text());

            i.sort();

            if (((i[0] == 1) && // instances that make up a large straight.
                 (i[1] == 2) &&
                 (i[2] == 3) &&
                 (i[3] == 4) &&
                 (i[4] == 5)) ||
                ((i[0] == 2) &&
                 (i[1] == 3) &&
                 (i[2] == 4) &&
                 (i[3] == 5) &&
                 (i[4] == 6))) {
                theScore = 40;
            }

            return theScore;
        }

        function calcChance() { // sums up the total score of the dice.
            var theScore = 0;

            theScore += parseInt($("#dice1").text())
                      + parseInt($("#dice2").text())
                      + parseInt($("#dice3").text())
                      + parseInt($("#dice4").text())
                       + parseInt($("#dice5").text());


            return theScore;
        }

        function calcYahtzee() {
            var theScore = 0;
            var dice = []; //the dice are put in an array

            dice[0] = parseInt($("#dice1").text());
            dice[1] = parseInt($("#dice2").text());
            dice[2] = parseInt($("#dice3").text());
            dice[3] = parseInt($("#dice4").text());
            dice[4] = parseInt($("#dice5").text());

            for (var i = 1; i <= 6; i++) {
                var Count = 0;
                for (var j = 0; j < 5; j++) {
                    if (dice[j] == i)
                        Count++;

                    if (Count > 4) { // if more than four dice are the have the same value you have a yahtzee.
                        theScore = 50;
                        alert("Yahtzee");
                    }
                }
            }
            return theScore;
        }

        function submitScore(totalScore) {
            $("#scoreTotal" + yourId).html(parseInt(totalScore));
        }

        function resetDice() {
            for (var i = 0; i < 6; i++) {
                $("#dice" + i).show();
                $("#dice" + i).html("Press roll button");
                $("#dice" + i + "Img").html("");
                $("#box" + i).prop('checked', false);
            }
            $("#rollScore").html(0);
        }

        $(function () {
            var group = '@(Model.ID)';
            var hub = $.connection.gameHub;
            var currentPlayer = 1; // Whos turn is it?
            var playerCap = '@(Model.PlayerCap)';
        var currentRound = 1;
        var totalRounds = 13;
        var numRolls = 0;
        var rollScore = 0;
        var totalScore = 0;
        var bonus = 0;
        var scoreId;
        var rollId;
        var yourId; // When yourId and currentPlayer are equal it is your turn

        function getLeaderId() {
            // Gets the id of the player in the lead
            var theId = 1;
            var topScore = 0;
            for (var i = 1; i <= playerCap; i++) {
                var playerTotalScore = parseInt($("#scoreTotal" + i.toString()).text())
                if (playerTotalScore > topScore) {
                    theId = i;
                    topScore = playerTotalScore;
                }
            }
            return theId;
        }

        function calcBonus() {
            // Calculates a bonus if there is one, returns 0 otherwise
            var theBonus = 0;
            var theTotalScore = 0;
            var lowerSection = [];

            lowerSection[0] = parseInt($("#scoreOnes" + yourId).text());
            lowerSection[1] = parseInt($("#scoreTwos" + yourId).text());
            lowerSection[2] = parseInt($("#scoreThrees" + yourId).text());
            lowerSection[3] = parseInt($("#scoreFours" + yourId).text());
            lowerSection[4] = parseInt($("#scoreFives" + yourId).text());
            lowerSection[5] = parseInt($("#scoreSixes" + yourId).text());

            for (var i = 0; i < 6; i++) {
                theTotalScore = theTotalScore + lowerSection[i];
                if (theTotalScore >= 63) {
                    theBonus = 35;
                    break;
                    // Return a bonus if the sum of the lower section is equal to or higher than 63
                }
            }
            return theBonus;
        }

        hub.client.showScore = function (scoreId, playerTotalScore, score) {
            // This function is called when someone else submits a score
            $(scoreId + currentPlayer).html(score);
            $("#scoreTotal" + currentPlayer).html(playerTotalScore);
            // Display the total score as well as the roll score in the scoreboard
            currentPlayer++;
            if (currentPlayer > playerCap) {
                // Case: Round is over
                currentPlayer = 1;
                currentRound++;
                if (currentRound > totalRounds) {
                    // Case: Game is over
                    bonus = calcBonus(); // Get the bonus
                    $("#scoreBonus" + yourId).html(bonus);
                    totalScore = totalScore + bonus;
                    $("#scoreTotal" + yourId).html(parseInt(totalScore));
                    hub.server.broadcastBonus(group, yourId, bonus);
                }
            }
            if (yourId == currentPlayer) {
                $("#turnInfo").html("<strong>Your turn!</strong>");
            }
        };

        hub.client.showBonus = function (playerId, theBonus) {
            $("#scoreBonus" + playerId).html(theBonus);
            var previousTotalScore = parseInt($("#scoreTotal" + playerId).text());
            var newTotalScore = parseInt(theBonus) + previousTotalScore;
            $("#scoreTotal" + playerId).html(newTotalScore);
            var leaderId = getLeaderId();
            hub.server.gameOver(leaderId);
        };

        hub.client.initPlayerId = function (theId) {
            // Each player receives a unique id
            yourId = parseInt(theId);
            if (yourId == currentPlayer) {
                $("#turnInfo").html("<strong>Your turn!</strong>");
            }
        }

        hub.client.addScorecard = function (players) {
            // Initialize the scorecard for all players
            // This function receives an array of all the player names
            var length = players.length;
            for (var i = 1; i <= length; i++) {
                var playerRow = $("<tr />");
                playerTd = $("<td />");
                playerTd.addClass("player" + i);
                playerTd.html('<strong>' + players[i - 1] + '</strong>');
                playerRow.append(playerTd);
                playerRow.append('<td id= "scoreOnes' + i + '"></td>');
                playerRow.append('<td id= "scoreTwos' + i + '"></td>');
                playerRow.append('<td id= "scoreThrees' + i + '"></td>');
                playerRow.append('<td id= "scoreFours' + i + '"></td>');
                playerRow.append('<td id= "scoreFives' + i + '"></td>');
                playerRow.append('<td id= "scoreSixes' + i + '"></td>');
                playerRow.append('<td id= "scoreTrips' + i + '"></td>');
                playerRow.append('<td id= "scoreQuads' + i + '"></td>');
                playerRow.append('<td id= "scoreBoat' + i + '"></td>');
                playerRow.append('<td id= "scoreSmallStraight' + i + '"></td>');
                playerRow.append('<td id= "scoreLargeStraight' + i + '"></td>');
                playerRow.append('<td id= "scoreChance' + i + '"></td>');
                playerRow.append('<td id= "scoreYahtzee' + i + '"></td>');
                playerRow.append('<td id= "scoreBonus' + i + '"></td>');
                playerRow.append('<td>=</td>');
                playerRow.append('<td id= "scoreTotal' + i + '"></td>');
                $("#players").append(playerRow);
            }
            $("#roll").show();
            $("#submit").show();
        };

        hub.client.broadcastMessage = function (username, message) {
            // This function is called when someone else posts a chat message
            var encodedName = $("<div />").text(username).html();
            var encodedMsg = $("<div />").text(message).html();
            $("#discussion").prepend('<li><strong>' + encodedName
                + '<strong>: &nbsp; &nbsp;' + encodedMsg + '</li>');
        };

        hub.client.showWin = function (leaderId) {
            // This function is called at the end of the game
            // This function receives the id of the player with the most points
            if (yourId == leaderId) {
                $("#yahtzeeGame").html("<strong>Congratulations, you won the game! Additional points have been added to your account</strong>");
            }
            else {
                $("#yahtzeeGame").html("<strong>Sorry, you lost the game, better luck next time</strong>");
            }
        }

        hub.client.hideYahtzee = function () {
            // This function is called if someone tries to join a game in progress
            $("#yahtzeeGame").html("<strong>This game is already in progress, please find another game in the lobby</strong>");
            $(".scorecard").hide();
        };

        $("#message").focus();

        $.connection.hub.start().done(function () {
            hub.server.join(group);
            $("#roll").hide();
            $("#submit").hide();

            $("#roll").click(function () {
                if (numRolls < 3 && yourId == currentPlayer) {
                    numRolls++;
                    if (numRolls == 3) {
                        $("#numberOfRolls").html("Please submit your score");
                    }
                    else {
                        $("#numberOfRolls").html(numRolls + 1);
                    }
                    rollDice();
                    // If it is your turn the dice is rolled when you press the roll button
                }
            });

            // The following shows the roll score to the user
            $("#ones").click(function () {
                rollId = this.id;
                scoreId = "#scoreOnes";
                rollScore = calcScore(1);
                $("#rollScore").html(rollScore);
            });
            $("#twos").click(function () {
                rollId = this.id;
                scoreId = "#scoreTwos";
                rollScore = calcScore(2);
                $("#rollScore").html(rollScore);
            });
            $("#threes").click(function () {
                rollId = this.id;
                scoreId = "#scoreThrees";
                rollScore = calcScore(3);
                $("#rollScore").html(rollScore);
            });
            $("#fours").click(function () {
                rollId = this.id;
                scoreId = "#scoreFours";
                rollScore = calcScore(4);
                $("#rollScore").html(rollScore);
            });
            $("#fives").click(function () {
                rollId = this.id;
                scoreId = "#scoreFives";
                rollScore = calcScore(5);
                $("#rollScore").html(rollScore);
            });
            $("#sixes").click(function () {
                rollId = this.id;
                scoreId = "#scoreSixes";
                rollScore = calcScore(6);
                $("#rollScore").html(rollScore);
            });
            $("#trips").click(function () {
                rollId = this.id;
                scoreId = "#scoreTrips";
                rollScore = calcTrips();
                $("#rollScore").html(rollScore);
            });
            $("#quads").click(function () {
                rollId = this.id;
                scoreId = "#scoreQuads";
                rollScore = calcQuads();
                $("#rollScore").html(rollScore);
            });
            $("#boat").click(function () {
                rollId = this.id;
                scoreId = "#scoreBoat";
                rollScore = calcBoat();
                $("#rollScore").html(rollScore);
            });
            $("#smallStraight").click(function () {
                rollId = this.id;
                scoreId = "#scoreSmallStraight";
                rollScore = calcSmallStraight();
                $("#rollScore").html(rollScore);
            });
            $("#largeStraight").click(function () {
                rollId = this.id;
                scoreId = "#scoreLargeStraight";
                rollScore = calcLargeStraight();
                $("#rollScore").html(rollScore);
            });
            $("#chance").click(function () {
                rollId = this.id;
                scoreId = "#scoreChance";
                rollScore = calcChance();
                $("#rollScore").html(rollScore);
            });
            $("#yahtzee").click(function () {
                rollId = this.id;
                scoreId = "#scoreYahtzee";
                rollScore = calcYahtzee();
                $("#rollScore").html(rollScore);
            });

            $("#submit").click(function () {
                // For when a player submits a score
                if (yourId == currentPlayer && rollId.length > 1) {
                    // If it is your turn and you have picked a valid score type
                    totalScore = totalScore + rollScore
                    hub.server.broadcastScore(group, scoreId, totalScore, rollScore); // Display the roll to others
                    $(scoreId + yourId).html(rollScore);
                    $("#scoreTotal" + yourId).html(parseInt(totalScore));
                    $("#" + rollId).hide(); // remove the score option that was picked
                    rollId = "";
                    if (playerCap > 1) {
                        $("#turnInfo").html("<strong>Please wait for your turn</strong>");
                    }
                    resetDice();
                    numRolls = 0; // Reset the dice and number of rolls
                    $("#numberOfRolls").html(numRolls + 1);
                    currentPlayer++;
                    if (currentPlayer > playerCap) {
                        // Case: A new round
                        currentPlayer = 1;
                        currentRound++;
                        if (currentRound > totalRounds) {
                            // Case: Game has ended
                            bonus = calcBonus();
                            $("#scoreBonus" + yourId).html(bonus);
                            totalScore = totalScore + bonus;
                            $("#scoreTotal" + yourId).html(parseInt(totalScore));
                            hub.server.broadcastBonus(group, yourId, bonus);
                            if (playerCap == 1) {
                                $("#yahtzeeGame").html("<strong>Game over!</strong>");
                            }
                        }
                    }
                }
            });

            $(document.body).delegate('#message', 'keypress', function (e) {
                // Enables users to send messages by clicking enter
                if (e.which === 13) { // if is enter
                    hub.server.send(group, $("#message").val());
                    $("#message").val("").focus();
                }
            });

            $("#sendmessage").click(function () {
                hub.server.send(group, $("#message").val());
                $("#message").val("").focus();
            });

            window.onbeforeunload = function () {
                var leaderId = getLeaderId();
                hub.server.handleQuit(group, leaderId);
            };

            $(window).unload(function () {
                if ($.browser.opera) {
                    var leaderId = getLeaderId();
                    hub.server.handleQuit(group, leaderId);
                }
            });
            // Previous 2 functions handle disconnects

        });
        });
    });
</script>